import React, {useEffect, useMemo, useState} from "react";
import {getRealtimeTrafficUsingGet} from "@/services/api-backend/trafficForecastController";
import ReactECharts from "echarts-for-react";
import {Button, Card, Col, Form, message, Row, Select, Space} from "antd";


export type Props = {
  infoVo: {id: number, name: string}[];
  type?:number
};

export  const RealtimeTraffic:React.FC<Props>=(props)=>{
  const {infoVo,type}=props
  const [interfaceNameList,setInterfaceNameList]=useState<{value: number, label: string}[]>([])
  const [data ,setData]=useState<API.TrafficForecastVo[]>([])
  const [loading,setLoading]=useState<boolean>(false)
  const [formRef] = Form.useForm();
  const [interfaceName,setInterfaceName]=useState<string>()
  // useEffect(() => {
  //   loadData(undefined)
  // }, []);
  useEffect(() => {
    if(infoVo&&infoVo.length>0){
      const items=infoVo.map(item=>({
        value:item.id!,
        label:item.name
      }))
      loadData()
      setInterfaceNameList(items)
    }
  }, [infoVo]);
  const loadData=async (id: number | null = null)=>{
    setLoading(true)
    try {
      const {data}=await getRealtimeTrafficUsingGet({
        interfaceId:id||undefined,type
      })

      if(data){
        setTimeout(()=>{
          if(id){
            setInterfaceName(data[0]?.interfaceName||null)
          }else{
            setInterfaceName(null)
          }
          setData(data)
        },2300)
      }
    }catch (e){
      message.error('实时流量监控数据（最近1小时）查询失败,',e)
    }finally {
      setTimeout(()=>setLoading(false),3000)
    }
  }

  const doSubmit=async (values)=>{
    await loadData(values?.interfaceId || null);
  }
  const doReset=async()=>{
      formRef.resetFields()
      await loadData()
  }
  /**
   * 数据转换函数
   * useMemo: 用于性能优化：缓存（记忆）计算结果，在依赖项未改变的情况下，避免重复计算，返回缓存的值。
   *          只有当它依赖的数据（dependencies）发生变化时，才重新计算；否则，直接返回上次计算的结果，避免不必要的计算开销。
   */
  const transformData = useMemo(() => {
    if (!data || data.length === 0) {
      return {
        timeLabels: [],
        interfaces: []
      };
    }

    // 获取所有唯一的接口ID
    const interfaceIds = Array.from(new Set(data.map(item => item.interfaceInfoId)));

    // 获取所有唯一的时间标签并排序
    const timeLabels = Array.from(new Set(data.map(item => item.timeLabel || ''))).sort();

    // 为每个接口构建数据
    const interfaces = interfaceIds.map(interfaceId => {
      const interfaceData = data.filter(item => item.interfaceInfoId === interfaceId);

      const interfaceName = interfaceData[0]?.interfaceName ;

      // 创建时间到数据的映射
      const dataMap = new Map<string, API.TrafficForecastVo>();
      interfaceData.forEach(item => {
        dataMap.set(item.timeLabel || '', item);
      });

      // 按时间标签填充数据
      const actualValues: (number | null)[] = [];
      const predictedValues: (number | null)[] = [];
      const latencyValues: (number | null)[] = [];
      const successRateValues: (number | null)[] = [];

      timeLabels.forEach(time => {
        const item = dataMap.get(time);
        actualValues.push(item?.actualRequestCount ?? null);
        predictedValues.push(item?.predictedRequestCount ?? null);
        latencyValues.push(item?.avgLatency ?? null);
        successRateValues.push(item?.successRate ?? null);
      });

      return {
        interfaceId,
        interfaceName,
        actualValues,
        predictedValues,
        latencyValues,
        successRateValues
      };
    });

    return {
      timeLabels,
      interfaces
    };
  }, [data]);

  const option = useMemo(() => {
    const { timeLabels, interfaces } = transformData;

    if (timeLabels.length === 0) {
      return {
        title: { text: '实时流量监控（最近1小时）', left: 'center' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: []
      };
    }

    const name = interfaceName ? `接口 ${interfaceName} 实时流量监控（最近1小时）` : '实时流量监控（最近1小时）';

    // 生成颜色数组
    const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];

    // 构建图例数据和系列数据
    const legendData: string[] = [];
    const series: any[] = [];

    interfaces.forEach((interfaceItem, index) => {
      const colorIndex = index % colors.length;
      const baseColor = colors[colorIndex];

      // 实际流量系列
      const actualSeriesName = interfaces.length > 1
        ? `${interfaceItem.interfaceName} - 实际流量`
        : '实际流量';
      legendData.push(actualSeriesName);
      series.push({
        name: actualSeriesName,
        type: 'line',
        data: interfaceItem.actualValues,
        itemStyle: { color: baseColor },
        lineStyle: { width: 3 },
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        areaStyle: {
          opacity: 0.25,
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: baseColor },
              { offset: 1, color: 'rgba(255,255,255,0.1)' }
            ]
          }
        },
        connectNulls: false,
        emphasis: {
          focus: 'series',
          itemStyle: { borderWidth: 2, borderColor: '#fff' }
        }
      });

      // 预测流量系列
      const predictedSeriesName = interfaces.length > 1
        ? `${interfaceItem.interfaceName} - 预测流量`
        : '预测流量';
      legendData.push(predictedSeriesName);
      series.push({
        name: predictedSeriesName,
        type: 'line',
        data: interfaceItem.predictedValues,
        itemStyle: { color: baseColor },
        lineStyle: { type: 'dashed', width: 2.5 },
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 5,
        connectNulls: false,
        emphasis: {
          focus: 'series',
          itemStyle: { borderWidth: 2, borderColor: '#fff' }
        }
      });
    });

    return {
      title: {
        text: name,
        left: 'center',
        textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' }
      },
      tooltip: {
        trigger: 'axis',
        triggerOn: 'click',  // 只在点击时触发
        enterable: true,  // 允许鼠标进入tooltip
        hideDelay: 300,  // 延迟隐藏，给用户时间操作tooltip
        backgroundColor: 'rgba(255, 255, 255, 0.96)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: { color: '#333', fontSize: 12 },
        padding: [8, 12],
        confine: true,
        axisPointer: {
          type: 'cross',
          label: { backgroundColor: '#6a7985' }
        },
        formatter: (params: any) => {
          if (!params || params.length === 0) return '';

          // 按接口分组
          const grouped = new Map();
          params.forEach((param: any) => {
            const parts = param.seriesName.split(' - ');
            const ifName = parts.length > 1 ? parts[0] : '当前接口';
            const type = parts.length > 1 ? parts[1] : param.seriesName;

            if (!grouped.has(ifName)) {
              grouped.set(ifName, {});
            }
            grouped.get(ifName)[type] = param;
          });

          // 限制显示数量
          const maxShow = 8;
          const totalCount = grouped.size;
          const showCount = Math.min(maxShow, totalCount);

          let result = `<div style="max-height: 400px; overflow-y: auto;">`;
          result += `<div style="padding-bottom: 6px; margin-bottom: 6px; border-bottom: 2px solid #eee;"><strong style="font-size: 13px;">${params[0].axisValue}</strong></div>`;

          let count = 0;
          grouped.forEach((types, ifName) => {
            // if (count >= maxShow) return;
            count++;

            result += `<div style="margin-bottom: 6px; padding: 4px 6px; background: #f9f9f9; border-radius: 4px;">`;
            result += `<div style="font-size: 11px; color: #888; margin-bottom: 2px;">${ifName}</div>`;

            const items = [];
            if (types['实际流量'] && types['实际流量'].value !== null) {
              const p = types['实际流量'];
              items.push(`<span style="color:${p.color};">●</span> 实际: <strong>${p.value?p.value:0}</strong>`);
            }
            if (types['预测流量'] && types['预测流量'].value !== null) {
              const p = types['预测流量'];
              items.push(`<span style="color:${p.color};">○</span> 预测: <strong>${p.value?p.value:0}</strong>`);
            }

            result += `<div style="font-size: 12px;">${items.join(' | ')}</div>`;
            result += `</div>`;
          });

          // if (totalCount > maxShow) {
          //   result += `<div style="text-align: center; color: #999; font-size: 11px; padding-top: 4px;">还有 ${totalCount - maxShow} 个接口未显示</div>`;
          // }
          result += `<div style="text-align: center; color: #999; font-size: 11px; padding-top: 4px;">共 ${totalCount} 个接口</div>`;

          result += `</div>`;
          return result;
        }
      },
      legend: {
        data: legendData,
        top: 40,
        type: 'scroll',
        orient: 'horizontal',
        left: '5%',
        right: '5%',
        pageButtonItemGap: 8,
        pageIconSize: 14,
        pageFormatter: '{current}/{total}',
        pageButtonGap: 10,
        animation: true,
        textStyle: { fontSize: 12 },
        icon: 'roundRect',
        itemWidth: 14,
        itemHeight: 10,
        itemGap: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        top: interfaces.length > 3 ? '22%' : '18%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeLabels,
        boundaryGap: false,
        axisLine: { lineStyle: { color: '#ddd' } },
        axisLabel: {
          rotate: 45,
          interval: timeLabels.length > 20 ? 'auto' : 0,
          color: '#666',
          fontSize: 11
        },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        name: '请求数',
        nameTextStyle: { color: '#666', fontSize: 12 },
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: '#666', fontSize: 11 },
        splitLine: { lineStyle: { color: '#f0f0f0', type: 'dashed' } }
      },
      series
    };
  }, [transformData, interfaceName]);

// 性能指标图表（延迟）
  const latencyOption = useMemo(() => {
    const { timeLabels, interfaces } = transformData;
    const name = interfaceName ? `接口 ${interfaceName} 平均延迟` : '平均延迟';

    // 生成颜色数组
    const colors = ['#91cc75', '#5470c6', '#fac858', '#ee6666', '#73c0de', '#3ba272'];

    const legendData: string[] = [];
    const series: any[] = [];

    interfaces.forEach((interfaceItem, index) => {
      const colorIndex = index % colors.length;
      const baseColor = colors[colorIndex];
      const seriesName = interfaces.length > 1
        ? `${interfaceItem.interfaceName}`
        : '平均延迟';
      legendData.push(seriesName);
      series.push({
        name: seriesName,
        type: 'line',
        data: interfaceItem.latencyValues,
        itemStyle: { color: baseColor },
        lineStyle: { width: 2.5 },
        smooth: true,
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          opacity: 0.2,
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: baseColor },
              { offset: 1, color: 'rgba(255,255,255,0.1)' }
            ]
          }
        },
        connectNulls: false,
        emphasis: {
          focus: 'series',
          itemStyle: { borderWidth: 2, borderColor: '#fff' }
        }
      });
    });

    return {
      title: {
        text: name,
        left: 'center',
        textStyle: { fontSize: 15, fontWeight: 'bold', color: '#333' }
      },
      tooltip: {
        trigger: 'axis',
        triggerOn: 'click',  // 只在点击时触发
        enterable: true,  // 允许鼠标进入tooltip
        hideDelay: 300,  // 延迟隐藏
        backgroundColor: 'rgba(255, 255, 255, 0.96)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: { color: '#333', fontSize: 12 },
        padding: [8, 12],
        confine: true,
        formatter: (params: any) => {
          if (!params || params.length === 0) return '';

          const maxShow = 8;
          const totalCount = params.length;
          // const showCount = Math.min(maxShow, totalCount);
          const showCount = totalCount;

          let result = `<div style="max-height: 350px; overflow-y: auto;">`;
          result += `<div style="padding-bottom: 4px; margin-bottom: 4px; border-bottom: 2px solid #eee;"><strong style="font-size: 13px;">${params[0].axisValue}</strong></div>`;

          for (let i = 0; i < showCount; i++) {
            const param = params[i];
            result += `<div style="padding: 2px 0; font-size: 12px;">`;
            result += `<span style="color:${param.color};font-size:14px;">●</span> `;
            result += `${param.seriesName}: <strong>${param.value !== null ? (param.value?param.value:0) + ' ms' : '-'}</strong>`;
            result += `</div>`;
          }

          // if (totalCount > maxShow) {
          //   result += `<div style="text-align: center; color: #999; font-size: 11px; padding-top: 4px; margin-top: 4px; border-top: 1px solid #eee;">+${totalCount - maxShow} 更多</div>`;
          // }
          result += `<div style="text-align: center; color: #999; font-size: 11px; padding-top: 4px; margin-top: 4px; border-top: 1px solid #eee;">共 ${totalCount} 个接口</div>`;
          result += `</div>`;
          return result;
        }
      },
      legend: {
        data: legendData,
        top: 35,
        type: 'scroll',
        orient: 'horizontal',
        left: '5%',
        right: '5%',
        pageButtonItemGap: 8,
        pageIconSize: 12,
        pageFormatter: '{current}/{total}',
        pageButtonGap: 10,
        animation: true,
        textStyle: { fontSize: 11 },
        icon: 'roundRect',
        itemWidth: 12,
        itemHeight: 8,
        itemGap: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        top: interfaces.length > 1 ? '26%' : '20%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeLabels,
        boundaryGap: false,
        axisLine: { lineStyle: { color: '#ddd' } },
        axisLabel: {
          rotate: 45,
          interval: timeLabels.length > 20 ? 'auto' : 0,
          color: '#666',
          fontSize: 10
        },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        name: '延迟(ms)',
        nameTextStyle: { color: '#666', fontSize: 11 },
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: '#666', fontSize: 10 },
        splitLine: { lineStyle: { color: '#f0f0f0', type: 'dashed' } }
      },
      series
    };
  }, [transformData, interfaceName]);

// 成功率图表
  const successRateOption = useMemo(() => {
    const { timeLabels, interfaces } = transformData;
    const name = interfaceName ? `接口 ${interfaceName} 成功率` : '成功率';

    // 生成颜色数组
    const colors = ['#fac858', '#5470c6', '#91cc75', '#ee6666', '#73c0de', '#3ba272'];

    const legendData: string[] = [];
    const series: any[] = [];

    interfaces.forEach((interfaceItem, index) => {
      const colorIndex = index % colors.length;
      const baseColor = colors[colorIndex];
      const seriesName = interfaces.length > 1
        ? `${interfaceItem.interfaceName}`
        : '成功率';
      legendData.push(seriesName);
      series.push({
        name: seriesName,
        type: 'line',
        data: interfaceItem.successRateValues,
        itemStyle: { color: baseColor },
        lineStyle: { width: 2.5 },
        smooth: true,
        symbol: 'circle',
        symbolSize: 5,
        areaStyle: {
          opacity: 0.2,
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: baseColor },
              { offset: 1, color: 'rgba(255,255,255,0.1)' }
            ]
          }
        },
        connectNulls: false,
        emphasis: {
          focus: 'series',
          itemStyle: { borderWidth: 2, borderColor: '#fff' }
        }
      });
    });

    return {
      title: {
        text: name,
        left: 'center',
        textStyle: { fontSize: 15, fontWeight: 'bold', color: '#333' }
      },
      tooltip: {
        trigger: 'axis',
        triggerOn: 'click',  // 只在点击时触发
        enterable: true,  // 允许鼠标进入tooltip
        hideDelay: 300,  // 延迟隐藏
        backgroundColor: 'rgba(255, 255, 255, 0.96)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: { color: '#333', fontSize: 12 },
        padding: [8, 12],
        confine: true,
        formatter: (params: any) => {
          if (!params || params.length === 0) return '';

          const maxShow = 8;
          const totalCount = params.length;
          // const showCount = Math.min(maxShow, totalCount);
          const showCount =totalCount;

          let result = `<div style="max-height: 350px; overflow-y: auto;">`;
          result += `<div style="padding-bottom: 4px; margin-bottom: 4px; border-bottom: 2px solid #eee;"><strong style="font-size: 13px;">${params[0].axisValue}</strong></div>`;

          for (let i = 0; i < showCount; i++) {
            const param = params[i];
            result += `<div style="padding: 2px 0; font-size: 12px;">`;
            result += `<span style="color:${param.color};font-size:14px;">●</span> `;
            result += `${param.seriesName}: <strong>${param.value !== null ? (param.value?param.value:0) + '%' : '-'}</strong>`;
            result += `</div>`;
          }

          // if (totalCount > maxShow) {
          //   result += `<div style="text-align: center; color: #999; font-size: 11px; padding-top: 4px; margin-top: 4px; border-top: 1px solid #eee;">+${totalCount - maxShow} 更多</div>`;
          // }
          result += `<div style="text-align: center; color: #999; font-size: 11px; padding-top: 4px; margin-top: 4px; border-top: 1px solid #eee;">共 ${totalCount} 个接口</div>`;
          result += `</div>`;
          return result;
        }
      },
      legend: {
        data: legendData,
        top: 35,
        type: 'scroll',
        orient: 'horizontal',
        left: '5%',
        right: '5%',
        pageButtonItemGap: 8,
        pageIconSize: 12,
        pageFormatter: '{current}/{total}',
        pageButtonGap: 10,
        animation: true,
        textStyle: { fontSize: 11 },
        icon: 'roundRect',
        itemWidth: 12,
        itemHeight: 8,
        itemGap: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        top: interfaces.length > 1 ? '26%' : '20%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeLabels,
        boundaryGap: false,
        axisLine: { lineStyle: { color: '#ddd' } },
        axisLabel: {
          rotate: 45,
          interval: timeLabels.length > 20 ? 'auto' : 0,
          color: '#666',
          fontSize: 10
        },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        name: '成功率(%)',
        nameTextStyle: { color: '#666', fontSize: 11 },
        min: 0,
        max: 100,
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: '#666', fontSize: 10 },
        splitLine: { lineStyle: { color: '#f0f0f0', type: 'dashed' } }
      },
      series
    };
  }, [transformData, interfaceName]);
  return <>

    {/*<Collapse*/}
    {/* defaultActiveKey={['1']}*/}
    {/* style={{marginBottom:24,background: token.colorBgContainer }}*/}
    {/* items={[*/}
    {/*  {*/}
    {/*    key:"1",*/}
    {/*    label:"查询条件",*/}
    {/*    children:<>*/}
    {/*    */}
    {/*    </>*/}
    {/*  }*/}

    {/*]} />*/}
    <Card style={{marginBottom:24}}>
      <Form
        form={formRef}
        layout="inline"
        onFinish={doSubmit}
        onReset={doReset}

        initialValues={{
          queryType: 'all',
          timeGranularity: 'day',
          modelType: 'prophet',
          includeConfidence: false,
        }}
      >
        <Form.Item
          label="接口"
          name="interfaceId"
        >
          <Select
            placeholder={"请选择接口（不选择则返回所有接口）"}
            allowClear
            style={{ width: 220 }}
            options={interfaceNameList}></Select>
        </Form.Item>
        {/* 提交按钮 */}
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              查询
            </Button>
            <Button htmlType="reset" disabled={loading}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
    {/* 流量对比图表 */}
    <Card
      title="流量对比"
      style={{ marginBottom: 16 }}
      // extra={<span style={{ fontSize: 12, color: '#999',cursor:"pointer" }}>💡 点击数据点查看详情</span>}
    >
      <ReactECharts
        option={option}
        style={{ height: '400px', width: '100%' }}
        opts={{ renderer: 'canvas' }}
        notMerge={true}
        showLoading={loading}
      />
    </Card>

    {/* 性能指标 - 两列布局 */}
    <Row gutter={16}>
      <Col span={12}>
        <Card
          title="平均延迟"
          // extra={<span style={{ fontSize: 11, color: '#999',cursor:"pointer" }}>💡 点击查看</span>}
        >
          <ReactECharts
            option={latencyOption}
            style={{ height: '300px', width: '100%' }}
            opts={{ renderer: 'canvas' }}
            showLoading={loading}
            notMerge={true}
          />
        </Card>
      </Col>
      <Col span={12}>
        <Card
          title="成功率"
          // extra={<span style={{ fontSize: 11, color: '#999',cursor:"pointer" }}>💡 点击查看</span>}
        >
          <ReactECharts
            option={successRateOption}
            style={{ height: '300px', width: '100%' }}
            opts={{ renderer: 'canvas' }}
            showLoading={loading}
            notMerge={true}
          />
        </Card>
      </Col>
    </Row>
  </>
}
